import grpc
import consul
from goods_srv.proto import goods_pb2_grpc, goods_pb2
from goods_srv.settings import settings


class GoodsTest:
    def __init__(self):
        # 连接grpc服务器
        c = consul.Consul(host="172.20.10.2", port=8500)
        services = c.agent.services()
        ip = ""
        port = ""
        for k, v in services.items():
            if v["Service"] == settings.SERVICE_NAME:
                ip = v["Address"]
                port = v["Port"]
                break

        channel = grpc.insecure_channel(f"{ip}:{port}")
        self.goods_stub = goods_pb2_grpc.GoodsStub(channel)

    def goods_list(self):
        rsp: goods_pb2.GoodsListResponse = self.goods_stub.GoodsList(
            goods_pb2.GoodsFilterRequest(keyWords="越南")
        )

        for item in rsp.data:
            print(item.name, item.shopPrice)

    def batch_get(self):
        ids = [421, 422]
        rsp: goods_pb2.GoodsListResponse = self.goods_stub.BatchGetGoods(
            goods_pb2.BatchGoodsIdInfo(id=ids)
        )

        for item in rsp.data:
            print(item.name, item.shopPrice)

    def get_detail(self, id):
        rsp = self.goods_stub.GetGoodsDetail(goods_pb2.GoodInfoRequest(id=id))
        
        print(rsp.name)

if __name__ == '__main__':
    goods = GoodsTest()
    # goods.goods_list()

    # goods.batch_get()
    goods.get_detail(421)
